﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Caching;
using System.Web.Hosting;

namespace FCMS.Caching
{
    public static class CacheManager
    {
        private static Cache m_cache;

        static CacheManager()
        {
            m_cache = HostingEnvironment.Cache;
        }

        public static void Insert<T>(string key, T value)
        {
            m_cache.Insert(key, value, null, DateTime.MaxValue, new TimeSpan(0, 100, 0));

        }

        public static T Get<T>(string key)
        {
            object obj = m_cache.Get(key);
            if (obj == null)
                return default(T);
            else
                return (T)obj;
        }

        public static void Remove(string key)
        {
            m_cache.Remove(key);
        }

        public static IList<string> GetKeys()
        {
            var keys = new List<string>();
            var e = m_cache.GetEnumerator();
            while (e.MoveNext())
            {
                keys.Add(e.Key.ToString());
            }
            return keys.AsReadOnly();
        }

        public static void RemoveAll()
        {
            IList<string> keys = GetKeys();
            foreach (string key in keys)
            {
                m_cache.Remove(key);
            }
        }

        public static IList<string> RegexSearch(string pattern)
        {
            IList<string> keys = GetKeys();
            IList<string> result = keys.Where(k =>
            {
                if (Regex.IsMatch(k, pattern))
                    return true;
                else
                    return false;
            }).ToList();
            return result;
        }
    }
}